package com.kingdee.eas.custom.tiog.service.bizwebser;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.attachment.AttachmentFtpFacadeFactory;
import com.kingdee.eas.base.attachment.BoAttchAssoCollection;
import com.kingdee.eas.base.attachment.BoAttchAssoFactory;
import com.kingdee.eas.base.attachment.BoAttchAssoInfo;
import com.kingdee.eas.base.attachment.IAttachmentFtpFacade;
import com.kingdee.eas.base.attachment.IBoAttchAsso;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.util.StringUtils;

/**
 * 
 * @title AttachmentDownloadFacadeControllerBean
 * @description 下载附件工具类
 * @author yacong_liu Email:yacong_liu@qq.com
 * @date 2020-3-23
 */
public class AttachmentDownloadFacadeControllerBean extends AbstractAttachmentDownloadFacadeControllerBean {
    private static Logger logger = Logger
            .getLogger("com.kingdee.eas.custom.tiog.service.bizwebser.AttachmentDownloadFacadeControllerBean");

    @Override
    protected List _download(Context ctx, String billId) throws BOSException, EASBizException {
        return listAttachment(ctx, billId);
    }

    /**
     * 
     * @title listAttachment
     * @description 获取单据对应的所有附件
     * @param ctx 上下文
     * @param billId 业务单据内码
     * @return List<Map<String, Object>>
     * @throws EASBizException
     * @throws BOSException
     */
    private List<Map<String, Object>> listAttachment(Context ctx, String billId) throws EASBizException,
            BOSException {

        if (StringUtils.isEmpty(billId)) {
            throw new EASBizException(EASBizException.CHECKBLANK, new Object[] { "单据内码" });
        }
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        IBoAttchAsso iBoAttchAsso = BoAttchAssoFactory.getLocalInstance(ctx); // 附件与业务对象关联
        BoAttchAssoCollection boAttchAssoCollection = iBoAttchAsso
                .getBoAttchAssoCollection(getEntityViewInfo(billId));

        if (boAttchAssoCollection == null || boAttchAssoCollection.size() <= 0) {
            log("单据内码: " + billId + "没有找到附件！");
            return list;
        }
        for (int i = 0; i < boAttchAssoCollection.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            BoAttchAssoInfo boAttchAssoInfo = boAttchAssoCollection.get(i);
            String id = boAttchAssoInfo.getId().toString();
            String attachmentId = boAttchAssoInfo.getAttachment().getId().toString();// 附件内码
            String fileName = boAttchAssoInfo.getAttachment().getName(); // 附件名
            String extName = boAttchAssoInfo.getAttachment().getSimpleName();// 附件扩展名
            byte[] content = downloadAttachment(ctx, attachmentId); // 文件流

            map.put("attachmentId", attachmentId);
            map.put("fileName", fileName);
            map.put("extName", extName);
            map.put("content", content);
            list.add(map);
        }
        return list;
    }

    /**
     * 
     * @title getFile
     * @description 保存文件到本地
     * @param content 文件流
     * @param filePath 本地目录
     * @param fileName 文件名
     */
    public static void getFile(byte[] content, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdir();
            }
            file = new File(filePath + File.separator + fileName);

            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(content);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

    /**
     * 
     * @title downloadAttachment
     * @description 获取附件文件流
     * @param ctx 应用上下文
     * @param attachmentId 附件内码
     * @return byte[]
     * @throws BOSException
     * @throws EASBizException
     */
    private byte[] downloadAttachment(Context ctx, String attachmentId) throws BOSException, EASBizException {
        if (StringUtils.isEmpty(attachmentId)) {
            throw new EASBizException(EASBizException.CHECKBLANK, new Object[] { "附件内码" });
        }
        IAttachmentFtpFacade iAttachmentFacade = AttachmentFtpFacadeFactory.getLocalInstance(ctx);
        byte[] content = null;
        try {
            content = iAttachmentFacade.downloadFile(attachmentId);
        } catch (EASBizException e) {
            e.printStackTrace();
            logger.error("下载附件失败！", e);
            throw new BOSException(e);
        }
        return content;
    }

    /**
     * 
     * @title getEntityViewInfo
     * @description 组装BoAttchAsso（附件与业务对象关联）查询视图
     * @param billId 业务单据内码
     * @return EntityViewInfo
     */
    private EntityViewInfo getEntityViewInfo(String billId) {
        EntityViewInfo evi = new EntityViewInfo();
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add(new SelectorItemInfo("id"));
        sic.add(new SelectorItemInfo("boID")); // 业务单据内码
        sic.add(new SelectorItemInfo("attachment.id")); // 附件内码
        sic.add(new SelectorItemInfo("attachment.name")); // 附件名称
        sic.add(new SelectorItemInfo("attachment.simpleName")); // 附件扩展名 eg: pdf jar

        FilterInfo filter = new FilterInfo();
        filter.getFilterItems().add(new FilterItemInfo("boID", billId, CompareType.EQUALS)); // 业务单据过滤
        evi.setSelector(sic);
        evi.setFilter(filter);
        return evi;
    }

    private void log(String log) {
        System.out.println("******".concat(log).concat("******"));
    }
}